let pathCond1 = getUrlParamToObj();
let channelId = pathCond1.channelId || 41;
let roleType = pathCond1.roleType || 1;
var path_video = path;
if (channelId) {
    $("#orderId").val(channelId);
}

var audioContext = new(window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window
    .msAudioContext)();
var uid = '';
var socket;
var recorder;
var caijiflag = true;
var cnt = 0;
var kongvoice;
var sendflag = false;
var kongvoice;
var cnt = 0;
var sendempty = false;
var isFinish = false; //判断是人为结束还是流程结束    false人为   true流程结束
var tabcell = $('.tabcell').text();
init();

function init() {
    EasyAjax.post_json({
        url: path_video + 'robotRecord/init/onRecord',
        //timeout: '60000',
        data: JSON.stringify({
            channelId : channelId,
            roleType : roleType    
        }),
    }, function(data) {
        startRecording();
        var obj = new Object();
        obj.channelId = channelId;
        obj.roleType = roleType;
        openChannel(obj);
    });
}
var heartCheck = {
    timeout: 3000,
    timeoutObj: null,
    serverTimeoutObj: null,
    start: function() {
        var self = this;
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(function() {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            socket.send("地瓜地瓜我是土豆，听到请回答！！！");
            // self.serverTimeoutObj = setTimeout(function() {
            //     // console.log(ws);
            //     socket.close();
            //     // createWebSocket();
            // }, self.timeout);

        }, this.timeout)
    }
}

var index_lay;


// 打开websocket
function openChannel(obj) {
    var wssurl = WS_SOCKET;
    var url = wssurl + 'audioMessage/' + obj.channelId + "/" + obj.roleType;
    console.log("url=" + url);
    socket = new WebSocket(url);
    socket.onopen = onChannelOpened;
    socket.onmessage = onChannelMessage;
    socket.onclose = onChannelClosed;
    socket.onerror = onChannelError;
}
// websocket打开
function onChannelOpened() {
    heartCheck.start();
    sendflag = true;
    // setTimeout(sendVoice, 5000);
    sendVoice();
}

var theTime = 0;
// websocket收到消息
function onChannelMessage(msg) {
    var data = msg.data;
    var datalen = msg.data.size;
    heartCheck.start();
    //停止录音  停止发送数据 
    // sendflag = false;
    // caijiflag = false;
    // sendempty = true;
    // setTimeout(sendVoice, 50000);
    // setTimeout(sleep, time);
    if (msg.data instanceof Blob) { // 处理二进制信息
        var reader = new FileReader();
        reader.onload = function(evt) {
            if (evt.target.readyState == FileReader.DONE) {
                var data = new Uint8Array(evt.target.result);
                audioContext.decodeAudioData(evt.target.result, function(buffer) {
                    //解码成pcm流
                    var audioBufferSouceNode = audioContext.createBufferSource();
                    audioBufferSouceNode.buffer = buffer;
                    audioBufferSouceNode.connect(audioContext.destination);
                    audioBufferSouceNode.start(0);

                }, function(e) {
                    // alert("Fail to decode the file.");
                });
            }
        }
        reader.readAsArrayBuffer(data);
    } else {
        console.log(data);
        if (data.indexOf("stop") != -1) { //处理文本
            //停止录音  停止发送数据 
            sendflag = false;
            caijiflag = false;
            sendempty = true;
            setTimeout(sendkongvoice, 220);
            var time = ((data.split("-")[1]) * 1000) - 1000;
            // var time = ((data.split("-")[1]*8)/(8*1000*24*1))*1000
            console.log('音频时长: ' + time);
            setTimeout(sleep, time);
        }
        if (data.indexOf("finish") != -1) { //处理文本
            //停止录音  停止发送数据
            sendflag = false;
            isFinish = true;
            stopRecording();
            setTimeout(finishRecording, 3000);
        }
    }
}
    // websocket异常
function onChannelError() {
    console.log("WebSocket连接发生错误");
}
// websocket关闭
function onChannelClosed(e) {
    //alert('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    sendflag == false;
    if (e.code != 1000) {
        //alert('连接异常' + e.code + ',点击确定进行重连')
        alert('网络环境差,请调整网络后重试！')
        location.reload();
        //phoneBack();
    }
}
// 发送信息
function sendMessage(message) {
    //var msgJson = JSON.stringify(message);
    socket.send(message);
    //console.log("发送信息 : " + msgJson);
}

function sleep() {
    sendflag = true;
    caijiflag = true;
    sendempty = false;
    console.log("传送")
    socket.send("on");
    setTimeout(sendVoice, 150);
}


function startRecording() {
    HZRecorder.get(function(rec) {
        recorder = rec;
        console.log(recorder)
        recorder.start();
    });
}

function stopRecording() {
    recorder.stop();
}

function finishRecording() {
    $("#videoStartRecord").click();
    sendflag = false;
}

function sendkongvoice() {
    if (sendempty == true) {
        socket.send(kongvoice);
        setTimeout(sendkongvoice, 180);
    }
}

function sendVoice() {
    // if (sendflag == true) {
        // console.log(555555555555)
        // console.log(recorder);
        if (typeof(recorder) != "undefined" && recorder != null) {
            // console.log(99999)
            var file = recorder.getBlob();
            if (cnt == 2) {
                kongvoice = file;
            }
            console.log(kongvoice);
            if (kongvoice != "undefined") {
                // console.log(999);
                console.log("file:"+file)
                socket.send(file);
                cnt++;
            }
        }
        setTimeout(sendVoice, 150);
        return true;
    // } else {
    //     return false;
    // }
}

// 关闭窗口退出
window.onbeforeunload = function() {
    sendMessage("off");
    socket.close();
}

$(function() {
    // layer.open({
    //     content: '<div class="vclintdlg"><dl><dt>温馨提示</dt><dd>录制过程中请您根据系统提示音，做出肯定回答，如‘同意’、‘明白’、‘已知晓’。回答不规范将导致视频审核失败需重新录制，请了解。</dd><dd class="queding">确定</dd></dl></div>',
    //     skin: 'msg'
    // });

    $('body').on('touchstart', '.queding', function() {
        layer.closeAll();
    })
})

navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia ||
    navigator.msGetUserMedia);